package otaku.gateway.core;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.util.concurrent.GenericFutureListener;
import otaku.gateway.config.ServerConfig;

import java.net.InetSocketAddress;

public class NettyDownStreamClient implements DownStreamClient {
    private NioEventLoopGroup group;
    private ChannelHandlerContext upstreamCtx;
    private Channel clientChannel;
    private ServerConfig serverConfig;

    public NettyDownStreamClient(ChannelHandlerContext upstreamCtx, ServerConfig serverConfig) {
        this.upstreamCtx = upstreamCtx;
        this.serverConfig = serverConfig;
    }

    @Override
    public void connect(InetSocketAddress remoteAddress) {
        Bootstrap bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpClientCodec())
                                .addLast(new HttpObjectAggregator(100000))
                                .addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
                                        FullHttpResponse copyResponse = msg.copy();
                                        for (var filter : serverConfig.getDownstreamResponseFilters()) {
                                            filter.filter(copyResponse);
                                        }
                                        replyToUpstream(copyResponse);
                                    }
                                });
                    }
                });
        bootstrap.connect(remoteAddress).addListener(new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    clientChannel = future.channel();
                } else {
                    stop();
                }
            }
        }).syncUninterruptibly();
    }

    @Override
    public void sendRequest(FullHttpRequest request) {
        clientChannel.writeAndFlush(request);
    }

    @Override
    public void replyToUpstream(FullHttpResponse response) {
        upstreamCtx.writeAndFlush(response).addListener(f -> {
            System.out.println("write downstream response back to client");
            stop();
        });
    }

    @Override
    public void stop() {
        group.shutdownGracefully();
    }
}
